//
//  ViewController.m
//  7.pthread_mutex-条件
//
//  Created by 梁森 on 2020/1/31.
//  Copyright © 2020 梁森. All rights reserved.
//

#import "ViewController.h"

#import <pthread.h>

@interface ViewController ()

@property (assign, nonatomic) pthread_mutex_t mutex;
@property (nonatomic, assign) pthread_cond_t  cond;

@property (nonatomic, strong) NSMutableArray *  mutableArr;


@end

@implementation ViewController

- (void)__initMutex:(pthread_mutex_t *)mutex
{
    // 递归锁：允许同一个线程对一把锁进行重复加锁
    // 初始化属性
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
    // 初始化锁
    pthread_mutex_init(mutex, &attr);
    // 销毁属性
    pthread_mutexattr_destroy(&attr);
    // 初始化条件
    pthread_cond_init(&_cond, NULL);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor greenColor];
    [self __initMutex:&_mutex];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self testCondition];
}

- (void)testCondition{
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 10; i ++) {
            [self add];
        }
    });
    dispatch_async(queue, ^{
        for (NSInteger i = 0; i < 10; i ++) {
            [self remove];
        }
    });
}
// 生产者消费者模式

- (void)add{
    pthread_mutex_lock(&_mutex);
    NSLog(@"%s---%@", __func__, [NSThread currentThread]);
    [self.mutableArr addObject:@"123"];
    NSLog(@"数组中的元素：%@", self.mutableArr);
    pthread_cond_signal(&_cond);
    pthread_mutex_unlock(&_mutex);
}
- (void)remove{
    pthread_mutex_lock(&_mutex);
    NSLog(@"%s---%@", __func__, [NSThread currentThread]);
    if (self.mutableArr.count == 0) {
        pthread_cond_wait(&_cond, &_mutex);
    }
    [self.mutableArr removeLastObject];
    NSLog(@"数组中的元素：%@", self.mutableArr);
    pthread_mutex_unlock(&_mutex);
}


- (NSMutableArray *)mutableArr{
    if (_mutableArr == nil) {
        _mutableArr = [NSMutableArray array];
    }
    return _mutableArr;
}

- (void)dealloc
{
    pthread_mutex_destroy(&_mutex);
    pthread_cond_destroy(&_cond);
}
@end
